<?php


namespace app\controllers;


use app\components\BaseAuthController;
use app\helpers\BinHelper;
use app\models\Group;
use app\models\GroupUser;
use app\models\User;
use Throwable;
use Yii;
use yii\db\Exception;
use yii\web\NotFoundHttpException;

class GroupController extends BaseAuthController {

    public $name = '用户组';

    public function actionIndex() {
        $model = new Group();
        $group_num = $this->getParam('group_num');
        if (!empty($group_num)) {
            $model->where = ['like', 'group_num', $group_num];
        }
        $dataProvider = $model->search([]);
        return $this->render(compact('dataProvider'));
    }

    /**
     * @param null $id
     * @return string
     * @throws Exception
     * @throws NotFoundHttpException
     */
    public function actionView($id = NULL) {
        $model = Group::findOne($id);
        if (!$model) {
//            Yii::$app->session->setFlash('error', '组不存在');
//            return $this->redirect(["{$this->id}/index"]);
            throw new NotFoundHttpException('组不存在');
        }

        $output = BinHelper::run('GroupGet', $model->group_num);
        if (is_array($output) && isset($output[1])) {
            Group::parseString($output[1]);
        }

        return $this->render(compact('model'));
    }

    /**
     * @param null $id
     * @return array|bool|string
     * @throws Exception
     * @throws NotFoundHttpException
     */
    public function actionSave($id = NULL) {
        /* @var $model Group */
        $model = $this->findModel($id, Group::class);
        if (!$model->load($this->post())) {
            return $this->render(compact('model'));
        }
        $res = $model->save();

        $output = BinHelper::run('GroupUpt', $model->group_num);
        $this->message($output);

        return $res;
    }

    public function actionDelete() {
        $id = $this->get('id');
        $model = Group::findOne($id);
        if (!$model) {
            Yii::$app->session->setFlash('error', '组不存在');
            return $this->redirect(["{$this->id}/index"]);
        }

        $group_num = $model->group_num;
        $file = FILE_ROOT . "/{$group_num}.group";

        try {
            if (!@unlink($file)) {
                throw new Exception("删除组文件: {$file}失败");
            }

            $model->delete();
            $groupUsers = GroupUser::find()->where(['group_num' => $group_num])->asArray()->all();
            foreach ($groupUsers as $groupUser) {
                /* @var $user User */
                $user = User::find()->where(['phone' => $groupUser['phone']])->one();
                User::generateFiles($user, FALSE);
            }

            GroupUser::deleteAll(['group_num' => $group_num]);

            $output = BinHelper::run('GroupDel', $group_num);
            $this->message($output);
        } catch (Exception $e) {
            Yii::$app->session->setFlash('error', $e->getMessage());
        } catch (Throwable $e) {
            Yii::$app->session->setFlash('error', $e->getMessage());
        }

        return $this->redirect(["{$this->id}/index"]);
    }

}